package pers.dawnyang.modular.system.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import pers.dawnyang.common.annotation.OperLog;
import pers.dawnyang.common.domain.Result;
import pers.dawnyang.common.domain.entity.SysConfig;
import pers.dawnyang.common.enums.OperType;
import pers.dawnyang.common.util.ResultUtil;
import pers.dawnyang.modular.system.domain.request.config.ConfigReqR;
import pers.dawnyang.modular.system.domain.request.config.ConfigReqU;
import pers.dawnyang.modular.system.service.ConfigService;

/**
 * 系统参数管理
 * 
 * @author dawn yang
 * @date 2021/05/08
 */

@RequestMapping("/sys/config")
@Controller
@Validated
public class ConfigController {

  @Autowired
  private ConfigService configService;

  @RequiresPermissions("sys:config:index")
  @GetMapping("/index")
  public String index() {
    return "/sys/config/index";
  }

  @RequiresPermissions("sys:config:edit")
  @GetMapping("/editView")
  public String editView(@RequestParam("id") Long id, ModelMap model) {
    SysConfig sysConfig = configService.getById(id);
    model.put("model", JSON.toJSONString(sysConfig));
    return "/sys/config/editView";
  }

  @PostMapping("/getPage")
  @ResponseBody
  public Result<Page<SysConfig>> getTreePage(Page<SysConfig> page, ConfigReqR req) {
    LambdaQueryWrapper<SysConfig> lqw = new LambdaQueryWrapper<>();
    lqw.like((StringUtils.isNotBlank(req.getConfigName())), SysConfig::getConfigName,
        req.getConfigName());
    lqw.like((StringUtils.isNotBlank(req.getConfigCode())), SysConfig::getConfigCode,
        req.getConfigCode());
    Page<SysConfig> pageRes = configService.page(page, lqw);
    return ResultUtil.success(pageRes);
  }

  @OperLog(operModul = "系统参数管理", operType = OperType.UPDATE)
  @RequiresPermissions("sys:config:edit")
  @PostMapping("/edit")
  @ResponseBody
  public Result<String> edit(@Validated ConfigReqU req) {
    SysConfig sysConfig = new SysConfig();
    BeanUtils.copyProperties(req, sysConfig);
    configService.updateById(sysConfig);
    configService.initConfigCache();
    return ResultUtil.success();
  }

}
